package doc.utils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author eollse
 */
public class BuildTree {

    public static <T> Tree<T> build(List<Tree<T>> nodes) {
        if (nodes == null) {
            return null;
        }
        List<Tree<T>> topNodes = new ArrayList<>();
        for (Tree<T> children : nodes) {
            String pid = children.getParentId();
            if (pid == null || "0".equals(pid)) {
                topNodes.add(children);
                continue;
            }
            nodes = setNode(nodes, pid, children);

        }
        return setRoot(topNodes);
    }

    /**
     * 设置根节点
     * @param topNodes
     * @param <T>
     * @return
     */
    private static <T> Tree<T> setRoot(List<Tree<T>> topNodes){
        Tree<T> root = new Tree<>();
        if (topNodes.size() == 1) {
            root = topNodes.get(0);
        } else {
            root.setId("-1");
            root.setParentId("");
            root.setHasParent(false);
            root.setChildren(true);
            root.setChecked(true);
            root.setChildren(topNodes);
            root.setText("顶级节点");
            Map<String, Object> state = new HashMap<>(1);
            state.put("opened", true);
            root.setState(state);
        }
        return root;
    }

    public static <T> List<Tree<T>> buildList(List<Tree<T>> nodes, String idParam) {
        if (nodes == null) {
            return null;
        }
        List<Tree<T>> topNodes = new ArrayList<>();
        for (Tree<T> node : nodes) {
            String pid = node.getParentId();
            //判断是否为顶级菜单，是则保存下来
            if (pid == null || idParam.equals(pid)) {
                topNodes.add(node);
                continue;
            }
            nodes = setNode(nodes, pid, node);
        }
        return topNodes;
    }

    /**
     * 设置子节点
     * @param nodes
     * @param pid
     * @param node
     * @param <T>
     */
    private static <T> List<Tree<T>> setNode(List<Tree<T>> nodes, String pid, Tree<T> node){
        for (Tree<T> tmpNode : nodes) {
            String id = tmpNode.getId();
            if (id != null && id.equals(pid)) {
                tmpNode.getChildren().add(node);
                node.setHasParent(true);
                tmpNode.setChildren(true);
                continue;
            }
        }
        return nodes;
    }
}